<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use Mine\MineModel;

/**
 * @property int $id 
 * @property int $crowd_sending_id 方案ID
 * @property int $robot_id 机器人
 * @property int $custom_total 客户数量
 * @property int $crowd_total 群数量
 * @property int $lose_total 流失数量
 * @property int $success_total 成功数量
 * @property int $fail_total 失败数量
 * @property int $complete_total 完成数量
 * @property int $status 0等待中 1执行中  2已完成 3暂停中  4已取消
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property int $is_loop
 * @property-read null|ChRobot $robot
 * @property-read null|ChCrowdSending $sending 
 */
class ChCrowdSendingSubTask extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_crowd_sending_sub_task';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'crowd_sending_id', 'robot_id', 'custom_total', 'crowd_total', 'lose_total', 'success_total', 'fail_total', 'complete_total', 'status', 'created_at', 'updated_at', 'is_loop'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'crowd_sending_id' => 'integer', 'robot_id' => 'integer', 'custom_total' => 'integer', 'crowd_total' => 'integer', 'lose_total' => 'integer', 'success_total' => 'integer', 'fail_total' => 'integer', 'complete_total' => 'integer', 'status' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'is_loop' => 'integer'];

    public static function setSubTask($robot_id,$crowd_sending_id,$custom_total=0,$crowd_total=0,$is_loop=0,$status=0,$lose_total=0)
    {
        $model=self::query() -> firstOrCreate(['robot_id'=>$robot_id,'crowd_sending_id'=>$crowd_sending_id,'is_loop'=>$is_loop],['status'=>$status]);
        if($custom_total){
            $model->increment('custom_total',$custom_total);
        }
        if($lose_total){
            $model->increment('lose_total',$lose_total);
        }
        if($crowd_total){
            $model->increment('crowd_total',$crowd_total);
        }
        return $model;
    }

    public function robot()
    {
        return $this -> hasOne(ChRobot::class,'id','robot_id');
    }

    public function sending()
    {
        return $this -> belongsTo(ChCrowdSending::class,'crowd_sending_id','id');
    }


}
